Page({
  data: {
    orderList: [],
    timer: null ,// 定时器
        islogin: false
  },
  ddtiaozhuan(event) {
    const orderId = event.currentTarget.dataset.id; // 获取当前订单的 ID
    const orderData = this.data.orderList.find(order => order._id === orderId); // 根据 ID 找到对应的订单数据
    
    if (orderData) {
      console.log('111111', orderData._id);
      const ddid = orderData._id; // 订单ID
  
      // 设置全局变量（如果需要）
      const app = getApp();
      app.globalData.orderData = orderData;
  
      // 跳转时携带参数
      wx.navigateTo({
        url: `/pages/ddxq/ddxq?ddid=${ddid}`
      });
    } else {
      wx.showToast({
        title: "订单数据异常",
        icon: "none"
      });
    }
  },
  
  
  onLoad() {
    this.action();
    this.getOrders(); // 页面加载时获取订单数据
      this.Islogin()
  },
  onShow(){
    this.getOrders();
    this.action();
      this.Islogin()
   console.log("sssssssssss123");
  },
   Islogin() {
        const openidRandom = wx.getStorageSync('openidRandom');
        if (openidRandom) {
          this.setData({
            islogin: true
          })
          console.log("islogin登录");
        } else {
          this.setData({
            islogin: false
          })
          console.log("islogin未登录");
        }
      },

  action() {
      const openidRandom = wx.getStorageSync('openidRandom');
      const db = wx.cloud.database();
  
      db.collection('users').where({
          _id: openidRandom
      }).get().then(res => {
          console.log("user", res.data);
          if (res.data.length > 0) {
              const openid = res.data[0]._openid;
              console.log("id", openid);
              return db.collection('orders').where({
                  _openid: openid
              }).get();
          } else {
              throw new Error("User not found");
          }
      }).then(res => {
          console.log("orders-res", res.data);
  
          if (!res.data || res.data.length === 0) {
              console.warn("订单数据为空");
              return;
          }
  
          this.setData({ orderList: res.data }, () => {
              console.log("orderList 更新成功", this.data.orderList);
              this.startCountdown(); // 重新启动倒计时
          });
      }).catch(error => {
          console.error("Error:", error);
      });
  }
,    
  startCountdown() {
    let that = this;

    if (that.data.timer) {
      clearInterval(that.data.timer);
    }
    that.data.timer = setInterval(() => {
      let updatedOrders = that.data.orderList.map(order => {
        let elapsedTime = Math.floor((Date.now() - order.createTime) / 1000);
        let remainingTime = 600 - elapsedTime;

        if (remainingTime <= 0) {
          return { ...order, payStatus: "支付超时", remainingTime: 0, displayTime: "" };
        } else {
          return { 
            ...order, 
            remainingTime, 
            displayTime: that.formatTime(remainingTime) 
          };
        }
      });

      that.setData({ orderList: updatedOrders });

      // 如果所有订单都超时，清除定时器
      if (updatedOrders.every(order => order.remainingTime === 0)) {
        clearInterval(that.data.timer);
      }
    }, 1000);
  },

  formatTime(seconds) {
    let min = Math.floor(seconds / 60);
    let sec = seconds % 60;
    return `${min}:${sec < 10 ? '0' : ''}${sec}`;
  },

// 获取订单数据
getOrders() {
  const that = this;
  wx.cloud.database().collection('orders') // 替换为你的集合名
    .get()
    .then(res => {
      that.setData({
        orderList: res.data
      });
    })
    .catch(err => {
      console.error("获取订单失败：", err);
    });
},

// 在 data 中添加一个新方法
// dingdan.js
// dingdan.js
goToPay(event) {
  const orderId = event.currentTarget.dataset.id; // 获取当前订单的 ID
  const orderData = this.data.orderList.find(order => order._id === orderId); // 根据 ID 找到对应的订单数据

  if (orderData) {
    // 设置全局变量
    const app = getApp();
    app.globalData.orderData = orderData;

    // 跳转到 xiangqing 页面
    wx.navigateTo({
      url: `/pages/xiangqing/xiangqing`
    });
  } else {
    wx.showToast({
      title: "订单数据异常",
      icon: "none"
    });
  }
},

// 取消订单
cancelOrder(event) {
  const orderId = event.currentTarget.dataset.id; // 获取订单ID
  console.log("订单id",orderId);
  const that = this;

  wx.showModal({
    title: '提示',
    content: '确定要取消订单吗？',
    success(res) {
      if (res.confirm) {
        wx.cloud.database().collection('orders') // 替换为你的集合名
          .doc(orderId)
          .remove()
          .then(() => {
            wx.showToast({ title: '订单已取消', icon: 'success' });

            // 更新本地数据，删除取消的订单
            const updatedOrderList = that.data.orderList.filter(order => order._id !== orderId);
            that.setData({ orderList: updatedOrderList });
          })
          .catch(err => {
            console.error("删除订单失败：", err);
            wx.showToast({ title: '取消失败', icon: 'error' });
          });
      }
    }
  });
},

  onUnload() {
    clearInterval(this.data.timer); // 清除定时器，避免内存泄漏
  }
});
